<template>
  <view class="my-publish-page">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="back-btn" @click="goBack">
		  <image src="/static/img/xiangzuojiantou.png" mode="" style="width: 25px;height: 25px;"></image>
      </view>
      <view class="title">我的发布</view>
      <view class="empty-btn"></view>
    </view>

    <!-- 加载状态 -->
    <view class="loading" v-if="loading">
      <text>加载中...</text>
    </view>

    <!-- 发布列表 -->
    <view class="publish-list" v-else>
      <!-- 有房源时渲染列表 -->
      <view v-if="houses.length > 0">
        <view class="publish-item" v-for="(house, index) in houses" :key="house.id || index">
          <!-- 图片区域 -->
          <view class="item-img">
            <image :src="house.images && house.images.length > 0 ? house.images[0] : '/static/sq.png'" mode="aspectFill"></image>
          </view>
          <!-- 文字信息区域：新增容器确保文字内部对齐 -->
          <view class="item-info">
            <view class="text-container">
              <view class="item-title">{{ house.title || '未命名房源' }}</view>
              <view class="item-desc">{{ `${house.houseType || '未知户型'}/${house.area || 0}/${house.direction || '未知朝向'}/${house.communityName || '未知小区'}` }}</view>
              <view class="tag-wrap">
                <view class="item-tag">近地铁</view>
                <view class="item-price">{{ house.rent || 0 }} 元/月</view>
              </view>
            </view>
          </view>
        </view>
        <!-- 底部提示 -->
        <view class="empty-tip">共{{ houses.length }}项，已加载全部</view>
      </view>
      
      <!-- 空状态 -->
      <view class="empty-state" v-else>
        <view class="empty-icon">🏠</view>
        <text class="empty-text">暂无发布房源</text>
        <button class="publish-btn" @click="goPublish">去发布</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { onShow } from '@dcloudio/uni-app';

// 状态管理
const houses = ref([]);
const loading = ref(true);

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 跳转到详情页
// const goDetail = (houseId) => {
//   // 这里可以根据实际需求跳转到房源详情页
//   uni.navigateTo({
//     url: `/ulit/detalispublish/detalispublish?id=${houseId}`
//   });
// };

// 跳转到发布页
const goPublish = () => {
  uni.navigateTo({
    url: '/ulit/housepublish/housepublish'
  });
};

// 获取房源列表
const fetchHouses = () => {
  loading.value = true;
  
  // 首先从本地存储获取数据，确保用户能看到自己的发布
  const localHouses = uni.getStorageSync('localHouses') || [];
  
  // 然后尝试从API获取数据
  uni.request({
    url: 'http://localhost:8080/user/houses',
    method: 'GET',
    success: (res) => {
      console.log('房源数据:', res);
      
      let apiHouses = [];
      // 根据实际接口返回的数据结构进行调整
      if (res.data && res.data.code === 200 && res.data.data) {
        apiHouses = res.data.data;
      } else if (Array.isArray(res.data)) {
        apiHouses = res.data;
      }
      
      // 合并本地数据和API数据，避免重复
      const mergedHouses = [...localHouses];
      
      // 将API数据中不在本地的项目添加到列表
      apiHouses.forEach(apiHouse => {
        // 检查是否已存在具有相同ID的房源
        const exists = mergedHouses.some(localHouse => 
          localHouse.id === apiHouse.id && !localHouse.isLocalOnly
        );
        if (!exists) {
          // 处理图片URL，确保使用完整域名
          if (apiHouse.images && Array.isArray(apiHouse.images)) {
            apiHouse.images = apiHouse.images.map(imgUrl => {
              if (imgUrl && !imgUrl.startsWith('http')) {
                return `http://localhost:8080${imgUrl.startsWith('/') ? '' : '/'}${imgUrl}`;
              }
              return imgUrl;
            });
          }
          mergedHouses.push(apiHouse);
        }
      });
      
      // 按创建时间倒序排序，最新的在前面
      mergedHouses.sort((a, b) => {
        const timeA = a.createdTime ? new Date(a.createdTime).getTime() : 0;
        const timeB = b.createdTime ? new Date(b.createdTime).getTime() : 0;
        return timeB - timeA;
      });
      
      houses.value = mergedHouses;
    },
    fail: (err) => {
      console.error('获取房源失败:', err);
      // API失败时，只使用本地存储的数据
      houses.value = localHouses;
      
      // 只有在本地也没有数据时才显示错误提示
      if (localHouses.length === 0) {
        uni.showToast({ title: '获取房源失败，显示本地数据', icon: 'none' });
      }
    },
    complete: () => {
      loading.value = false;
    }
  });
};

// 组件挂载时获取数据
onMounted(() => {
  fetchHouses();
});

// 页面显示时检查登录状态和刷新数据
onShow(() => {
  // 检查登录状态
  const token = uni.getStorageSync('token');
  if (!token) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    });
    // 返回上一页
    setTimeout(() => {
      uni.navigateBack();
    }, 1000);
    return;
  }
  fetchHouses();
});

// 页面显示时刷新数据（确保从发布页面返回时能看到最新数据）
uni.$on('refreshHouses', () => {
  fetchHouses();
});

// 页面卸载时移除事件监听
onUnmounted(() => {
  uni.$off('refreshHouses');
});
</script>

<style scoped>
/* 页面整体布局 */
.my-publish-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f8f8f8;
}

/* 导航栏 */
.nav-bar {
  display: flex;
  align-items: center;
  height: 88rpx;
  border-bottom: 1rpx solid #eee;
  padding: 0 30rpx;
}
.back-btn {
  width: 44rpx;
  height: 44rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
.back-icon {
  font-size: 36rpx;
  color: #008080;
}
.title {
  flex: 1;
  text-align: center;
  font-size: 36rpx;
  font-weight: bold;
  color: #008080;
}
.empty-btn {
  width: 44rpx;
}

/* 发布列表：核心优化图文对齐 */
.publish-list {
  flex: 1;
  padding: 20rpx;
}
.publish-item {
  display: flex;
  align-items: center; /* 图片与文字区域垂直居中对齐 */
  background-color: #fff;
  border-radius: 12rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  margin-bottom: 20rpx;
}
.item-img {
  width: 200rpx;
  height: 150rpx;
  overflow: hidden;
}
.item-img image {
  width: 100%;
  height: 100%;
}
.item-info {
  flex: 1;
  padding: 20rpx;
}
/* 文字容器：确保文字内部垂直分布均匀 */
.text-container {
  display: flex;
  flex-direction: column;
  gap: 10rpx; /* 统一文字间间距，替代原margin-top */
}
.item-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}
.item-desc {
  font-size: 26rpx;
  color: #999;
}
/* 标签与价格容器：水平对齐 */
.tag-wrap {
  display: flex;
  align-items: center; /* 标签与价格垂直居中 */
  gap: 12rpx; /* 标签与价格间距 */
}
.item-tag {
  display: inline-block;
  font-size: 24rpx;
  color: #008080;
  background-color: rgba(0, 128, 128, 0.1);
  padding: 4rpx 12rpx;
  border-radius: 4rpx;
}
.item-price {
  font-size: 32rpx;
  color: #e53935;
  font-weight: bold;
}

/* 加载状态 */
.loading {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  color: #999;
}

/* 空状态 */
.empty-state {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-icon {
  font-size: 120rpx;
  margin-bottom: 40rpx;
}

.empty-text {
  font-size: 30rpx;
  color: #999;
  margin-bottom: 40rpx;
}

.publish-btn {
  background-color: #008080;
  color: #fff;
  width: 200rpx;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 40rpx;
  font-size: 28rpx;
}

/* 底部提示 */
.empty-tip {
  text-align: center;
  font-size: 28rpx;
  color: #999;
  padding: 30rpx 0;
}
</style>